import { Toast } from 'antd-mobile'
import {reqregister} from '../../http/api'

//State
 const initState = {
    //1初始化
    user: {
        phone: '',
        nickname: '',
        password: ''
    }
}
//action type 
const TYPES = {
    //2修改user的type
    REGISTER_CHANGE_USER:'REGISTER_CHANGE_USER'
}
//reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        //action={type:'REGISTER_CHANGE_USER',key='phone',value='123'}
        // 3.修改user的reducer
        case TYPES.REGISTER_CHANGE_USER:
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
        default:
            return state;
    }
}
//action creator
export const actions = {
    //4修改user的action
    changeUser:(key,value)=>({type:TYPES.REGISTER_CHANGE_USER,key,value}),
    //6注册逻辑
    doRegister:(push)=>{
        return (dispatch,getState)=>{
            //获取user
            let user=getUser(getState())
            reqregister(user).then(res=>{
                if(res.data.code===200){
                    //弹成功
                    Toast.show({
                        content:res.data.msg
                    })
                    //跳转
                    push('/login')
                }
            })
        }
    }
}

//selector导出数据给组件
//5导出user
export const getUser =state=>state.register.user;


//导出
export default reducer;